﻿using log4net;
using Microsoft.AspNetCore.Builder;
using suirui.ZhuMu.Common;
using System;
using System.IO;
using System.Linq;
using static suirui.ZhuMu.Framework.CustomApiVersion;

namespace suirui.ZhuMu.Framework
{
    /// <summary>
    /// Swagger中间件
    /// </summary>
    public static class SwaggerMildd
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(SwaggerMildd));
        //public static void UseSwaggerMildd(this IApplicationBuilder app, Func<Stream> streamHtml)
        public static void UseSwaggerMildd(this IApplicationBuilder app)
        {
            if (app == null) throw new ArgumentNullException(nameof(app));

            /*
            app.UseSwagger(config => { });
            app.UseSwaggerUI(config =>
            {
                config.SwaggerEndpoint("/swagger/v1/swagger.json", "Zhumu Api v1");
            });*/

            
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                //根据版本名称倒序 遍历展示
                var ApiName = Appsettings.app(new string[] { "Startup", "ApiName" });
                typeof(ApiVersions).GetEnumNames().OrderByDescending(e => e).ToList().ForEach(version => 
                {
                    c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"{ApiName} {version}");
                });

                c.HeadContent = @$"<script async='async' id='mini-profiler' src='/profiler/includes.min.js?v=4.1.0+c940f0f28d'
                                    data-version='4.1.0+c940f0f28d' data-path='/profiler/'
                                    data-current-id='4ec7c742-49d4-4eaf-8281-3c1e0efa8888' data-ids='4ec7c742-49d4-4eaf-8281-3c1e0efa8888'
                                    data-position='Left'
                                    data-authorized='true' data-max-traces='5' data-toggle-shortcut = 'Alt+P'
                                    data-trivial-milliseconds='2.0' data-ignored-duplicate-execute-types = 'Open,OpenAsync,Close,CloseAsync' >
                                  </script>";

                //// 将swagger首页，设置成我们自定义的页面，记得这个字符串的写法：{项目名.index.html}
                //if (streamHtml.Invoke() == null)
                //{
                //    var msg = "index.html的属性，必须设置为嵌入的资源";
                //    log.Error(msg);
                //    throw new Exception(msg);
                //}
                //c.IndexStream = streamHtml;

                //路径配置，设置为空，表示直接在根域名（localhost: 8001）访问该文件,注意localhost: 8001 / swagger是访问不到的，去launchSettings.json把launchUrl去掉，如果你想换一个路径，直接写名字即可，比如直接写c.RoutePrefix = "doc";
                //c.RoutePrefix = "doc";
            });
        }
    }
}
